<template>
  <van-loading v-if="loading" style="display:flex;align-items:center;justify-content:center;height:80vh" size="24px" vertical>加载中...
  </van-loading>
  <div v-else>
    <van-empty style="display:flex; justify-content:center; align-items:center; height: 70vh;" v-if="teamList.length === 0"
               description="什么也没找到～"/>
    <div v-else>
      <van-card
          v-for="item in teamList"
          :desc="item.teamDescription"
          :title="item.teamName"
          :tag="`队长-${item.userId === loginUserId ? '我' : item.userName}`"
          :thumb="item.userAvatar"
      >
        <template #tags>
          <van-tag style="margin: 10px 10px 10px 0" plain :type="item.teamStatus === 0 ? 'success' : 'danger'">
            {{ item.teamStatus === 0 ? '公开' : item.teamStatus === 1 ? '加密' : null }}
          </van-tag>
          <van-tag style="margin: 10px 10px 10px 0" plain type="danger" v-if="item.ifExpired">
            已过期
          </van-tag>
        </template>
        <template #bottom>
          <p>{{ `人数：${item.currentNum}/${item.maxNum}` }}</p>
          <p>{{ `截止时间：${new Date(item.expireTime).toLocaleString()}` }}</p>
        </template>
        <template #footer>
          <van-button plain type="primary" v-if="item.userId !== loginUserId && item.ifMember === false" size="small"
                      @click="joinTeam(item.teamId, item.teamStatus)">加入队伍
          </van-button>
          <van-button plain v-if="item.userId === loginUserId" size="small" @click="updateTeam(item.teamId)">更新队伍</van-button>
          <van-button plain type="warning" v-if="item.ifMember || item.userId === loginUserId" size="small"
                      @click="quitTeam(item.teamId, item.userId, item.currentNum)">退出队伍
          </van-button>
          <van-button plain type="danger" v-if="item.userId === loginUserId" size="small" @click="deleteTeam(item.teamId)">解散队伍
          </van-button>
        </template>
        <template #num v-if="isMine">
          <van-icon size="20" name="friends-o" @click="toTeamMember(item.teamId)"/>
        </template>
      </van-card>
      <van-pagination v-if="total > 0"
                      v-model="pageNum"
                      @change="handlePageChange"
                      :page-count="Math.ceil(total / pageSize)"
                      mode="simple"/>
    </div>
    <div>
      <van-action-sheet
          :description="desc"
          v-model:show="show"
          :actions="actions"
          cancel-text="取消"
          close-on-click-action
          @select="onSelect"
      />
    </div>
    <van-dialog :before-close="onBeforeClose" v-model:show="showPassword" title="队伍密码" show-cancel-button>
      <van-field
          name="password"
          v-model="password"
          type="password"
          placeholder="请输入"
      />
    </van-dialog>
  </div>
</template>

<script setup lang="ts">

import {defineEmits, defineProps} from "@vue/runtime-core";
import {ref} from "vue";
import myAxios from "../plugins/myAxios";
import {showSuccessToast} from "vant/lib/toast/function-call";
import {closeToast, showFailToast} from "vant";
import {showLoadingToast} from "vant/es";
import {useRouter} from "vue-router";

const props = defineProps({
  teamList: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Boolean,
    default: true
  },
  showPassword: {
    type: Boolean,
    default: false
  },
  loginUserId: {
    type: Number,
    default: ''
  },
  isMine: {
    type: Boolean,
    default: false
  },
  pageSize: {
    type: Number,
    default: 10
  },
  total: {
    type: Number,
    default: 0
  }
});
const emit = defineEmits(['getTeamList', 'handlePageChange']);

// 分页
const pageNum = ref(1);
const handlePageChange = (page: number) => {
  pageNum.value = page;
  emit('handlePageChange', page);
};

// 加入队伍
const teamId = ref(null);
const showPassword = ref(false);
const password = ref('');
const joinTeamApi = async () => {
  const res = await myAxios.post('/team-manage/join', {
    id: teamId.value,
    password: password.value
  }) as any;
  if (res) {
    showSuccessToast('加入成功');
    emit('getTeamList');
  }
};
const joinTeam = (id: number, teamStatus: number) => {
  teamId.value = id as any;
  password.value = '';
  if (teamStatus == 1) {
    showPassword.value = true;
  } else {
    joinTeamApi();
  }
}
const onBeforeClose = (action: string) => {
  if (action === 'cancel') {
    return true;
  }
  if (password.value === '') {
    showFailToast('请输入密码');
    return false;
  }
  if (!password.value.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,10}$/)) {
    showFailToast('密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在8-10之间');
    return false;
  }
  joinTeamApi();
  return true;
};

// 退出队伍 & 解散队伍
const actions = ref([]);
const desc = ref('');
const show = ref(false);
const url = ref('');
const quitTeam = async (id: number, userId: number, currentNum: number) => {
  teamId.value = id as any;
  url.value = '/team-manage/quit';
  actions.value = [
    {name: '退出队伍', color: '#ee0a24'}
  ];
  if (currentNum === 1) {
    desc.value = '当前队伍仅剩你一人，退出后队伍将自动解散';
  } else {
    if (userId === props.loginUserId) {
      desc.value = '你当前是队长，退出后将自动按加入时间顺序转移队长身份';
    } else {
      desc.value = '退出队伍后将无法恢复';
    }
  }
  show.value = true;
};
const deleteTeam = async (id: number) => {
  teamId.value = id as any;
  url.value = '/team-manage/disband';
  actions.value = [
    {name: '解散队伍', color: '#ee0a24'}
  ];
  desc.value = '解散队伍后将无法恢复';
  show.value = true;
};
const onSelect = async () => {
  show.value = false;
  showLoadingToast({message: '处理中...', forbidClick: true, duration: 0});
  const res = await myAxios.post(url.value, {
    id: teamId.value
  }) as any;
  if (res) {
    closeToast();
    showSuccessToast('操作成功');
    emit('getTeamList');
  }
}

// 更新队伍
const router = useRouter();
const updateTeam = (teamId: number) => {
  router.push({
    path: '/save-team',
    query: {
      teamId: teamId
    }
  });
};

// 跳转到队伍成员页面
const toTeamMember = (teamId: number) => {
  router.push({
    path: '/team-member',
    query: {
      teamId: teamId
    }
  });
};

</script>
